<?php

namespace app\admin\controller;

use app\common\Helper;
use app\admin\model\User;
use app\admin\model\Store;
use app\admin\model\Storesettlement;
use app\admin\model\Usersettlement;

use app\common\validate\BaseValidate;
use app\admin\service\Pay as PayService;
use app\admin\service\WxNotify;

use app\common\validate\WithdrawPay;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 提现
 */
class Withdraw extends Base
{

    public function _initialize()
    {
        parent::_initialize();

    }

    /**
     * 首页
     */
    public function getHomeFrame(){
        $startMonth = date("Y-m-01");
        $endMonth = date("Y-m-01 23:59:59")." +1 month -1 day";

        $where = [];
        if($this->admin->roleType != 1){
            $where['s.province'] = $this->admin->province;
            if($this->admin->city != '所有') {
                $where['s.city'] = $this->admin->city;
            }
        }
        // 累计提现
        $withdrawWhere = [
            'a.status' => 1,
        ];
        // 店铺提现
        $join = [
            ['store s', 's.id = a.storeId']
        ];
        $storeWithdraw = Storesettlement::alias('a')->where($where)->where($withdrawWhere)->join($join)->sum('amount');
        // 用户提现
        $userWithdraw = Usersettlement::alias('a')->where($withdrawWhere)->sum('amount');
        $totalWithdraw = ($storeWithdraw + $userWithdraw);
        $totalWithdraw2 = round($totalWithdraw * (1 - self::WX_FEE)); // 微信收取费用

        // 本月提现
        $monthWithdrawWhere = [
            'a.status' => 1,
            'a.settleTime' => ['between time', [$startMonth, $endMonth]]
        ];
        // 店铺提现
        $monthStoreWithdraw = Storesettlement::alias('a')->where($where)->where($monthWithdrawWhere)->join($join)->sum('amount');
        // 用户提现
        $monthUserWithdraw = Usersettlement::alias('a')->where($monthWithdrawWhere)->sum('amount');
        $monthWithdraw = ($monthStoreWithdraw + $monthUserWithdraw);
        $monthWithdraw2 = round($monthWithdraw * (1 - self::WX_FEE)); // 微信收取费用

        // 昨日提现
        $dayWithdrawWhere = [
            'a.status' => 1,
        ];
        // 店铺提现
        $dayStoreWithdraw = Storesettlement::alias('a')->where($where)->where($dayWithdrawWhere)->whereTime('settleTime', 'yesterday')->join($join)->sum('amount');
        // 用户提现
        $dayUserWithdraw = Usersettlement::alias('a')->where($dayWithdrawWhere)->whereTime('settleTime', 'yesterday')->sum('amount');
        $dayWithdraw = ($dayStoreWithdraw + $dayUserWithdraw);
        $dayWithdraw2 = round($dayWithdraw * (1 - self::WX_FEE)); // 微信收取费用

        $data = [
            'totalWithdraw' => $totalWithdraw ? : '',
            'totalWithdraw2' => $totalWithdraw2 ? : '',
            'monthWithdraw' => $monthWithdraw ? : '',
            'monthWithdraw2' => $monthWithdraw2 ? : '',
            'dayWithdraw' => $dayWithdraw ? : '',
            'dayWithdraw2' => $dayWithdraw2 ? : '',
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 列表
     */
    public function getList(){
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }
        if (empty($param->status)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'status 不能为空');
        }
        if (!in_array($param->status, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'status 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $defaultWhere = [];
        $where = $defaultWhere;
        if($param->status == 1){
            // 已支付
            $where['a.status'] = 1;
        }else{
            // 待支付
            $where['a.status'] = ['in', '0,2'];
        }
        if (isset($param->storeName)) {
            $where['b.name'] = ['like', '%' . $param->storeName . '%'];
        }
        if (isset($param->userName)) {
            $where['b.userName'] = ['like', '%' . $param->userName . '%'];
        }

        if($param->type == 1){
            if($this->admin->roleType != 1){
                $where['b.province'] = $this->admin->province;
                if($this->admin->city != '所有') {
                    $where['b.city'] = $this->admin->city;
                }
            }
            // 店铺提现
            $model = new Storesettlement();
            $join = [
                ['store b', 'b.id = a.storeId']
            ];
            $field = 'a.*, b.name as storeName, b.imgUrl';
        }else{
            // 分销会员提现
            $model = new Usersettlement();
            $join = [
                ['user b', 'b.id = a.userId']
            ];
            $field = 'a.*, b.userName, b.imgUrl, b.phone';
        }
        $order = '';
        $result = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->order($order)->select();
        $total = $model->alias('a')->where($where)->join($join)->count();
        $totalWithdraw = $model->alias('a')->where($where)->join($join)->sum('a.amount');
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关提现');
        }

        foreach($result as $item){
            /*if(isset($item['storeId'])){
                $storeInfo = Store::where(['id' => $item['storeId']])->field('name,imgUrl')->find();
                $item['storeName'] = $storeInfo['name'];
                $item['imgUrl'] = $storeInfo['imgUrl'];
            }
            if(isset($item['userId'])){
                $userInfo = User::where(['id' => $item['userId']])->field('userName,imgUrl,phone')->find();
                $item['userName'] = $userInfo['userName'];
                $item['imgUrl'] = $userInfo['imgUrl'];
                $item['phone'] = $userInfo['phone'];
            }*/

            $item['amount2'] = round($item['amount'] * (1 - self::WX_FEE)); // 微信收取费用
        }

        //return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
        $data = [
            'status' => config('status.SUCCESS_STATUS'),
            'message' => self::MSG_SUCCESS,
            'data' => $result,
            'totalWithdraw' => $totalWithdraw,
            'total' => $total
        ];
        return json($data);
    }

    /**
     * 支付
     */
    public function pay(Request $request){
        (new WithdrawPay())->goCheck();
        $param = $request->param();
        $pay = new PayService($param);
        return $pay->shanghuPay();
    }


}